define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts', 'echarts-theme', ], function ($, undefined, Backend, Table, Form,Echarts) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'caijiaku/material_inventory/index' + location.search,
                    add_url: 'caijiaku/material_inventory/add',
                    edit_url: 'caijiaku/material_inventory/edit',
                    del_url: 'caijiaku/material_inventory/del',
                    multi_url: 'caijiaku/material_inventory/multi',
                    import_url: 'caijiaku/material_inventory/import',
                    table: 'material_inventory',
                }
            });

            var table = $("#table");
            var category = Config.categorylist;
            var oneCate = [];
            var twoCate = [];
            var threeCate = [];
            Fast.config.openArea = ['100%','100%'];
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                height:700,
                fixedColumns: true,
                fixedRightNumber: 1,
                fixedNumber: 2,
                searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                pageList:[10, 30, 50, 100, 'All'],
                columns: [
                    [
                        {checkbox: true,formatter: function(value, row, index) {
                            return {
                                disabled: !(Config.childrenAdminIds.indexOf(row.admin_id) > -1)
                            };
                        }},
                        // {field: 'id', title: __('Id'), operate:false},
                        
                        {field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'project_name', title: __('Project_name'), operate: 'LIKE', formatter: Table.api.formatter.search},
                        {field: 'material_name', title: __('Material_name'), operate: false, table: table, class: 'autocontent'},
                        {field: 'own_spec', title: __('Own_spec'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'unit', title: __('Unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'showdate', title: __('Showdate'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, sortable:true},
                        {field: 'price', title: __('Price')+"(含税)", operate:false},
                        // {field: 'notaxprice', title: __('Price')+"(除税)", operate:false},
                        {field: 'price', title: __('走势图'), operate:false,formatter:Controller.api.formatter.trend},
                        {field: 'tax', title: __('Tax'), operate:false},
                        {field: 'faxnum', title: __('Faxnum')+"(含税)", operate:false,formatter:Controller.api.formatter.faxtab},
                        {field: 'govnum', title: __('Govnum')+"(含税)", operate:false,formatter:Controller.api.formatter.govtab},
                        {field: 'mixnum', title: __('专业测定价')+"(含税)", operate:false,formatter:Controller.api.formatter.mixtab},
                        {field: 'inquirynum', title: __('Inquirynum')+"(含税)", operate:false,formatter:Controller.api.formatter.inquirytab},
                        {field: 'images', title: __('Images'),operate:false,formatter:Table.api.formatter.images},
                        {field: 'areaname', title: __('Areaname'), operate: 'LIKE'},
                        {field: 'brandname', title: __('Brandname'), operate: 'LIKE'},
                        {field: 'admin_id', title: __('数据来源'), formatter:function(value,row,index){
                            return row.admin.nickname
                        }},
                        {field: 'lock_code', title: __('Lock_code'), operate: 'LIKE', formatter: Table.api.formatter.search},
                        // {field: 'source', title: __('Source'), searchList: { "0": __('Source 0'), "1": __('Source 1') }, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, sortable:true, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons: [{
                            name: 'detail',
                            text: __('一键询价'),
                            icon: 'fa fa-list',
                            classname: 'btn btn-info btn-xs',
                            url: function (row, column) { //row 表格接收到的数据
                                // return 'javascript:;';
                                return "material_inventory/gotocjt?ids="+ row.id; //跳转材价通
                            },
                            extend:' target="_blank"',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1 && Config.enableGotocjt;
                            }
                        },{
                            name: 'edit',
                            icon: 'fa fa-pencil',
                            title: __('Edit'),
                            extend: 'data-toggle="tooltip" data-container="body"',
                            classname: 'btn btn-xs btn-success btn-editone',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1;
                            }
                        },{
                            name: 'del',
                            icon: 'fa fa-trash',
                            title: __('Del'),
                            extend: 'data-toggle="tooltip" data-container="body"',
                            classname: 'btn btn-xs btn-danger btn-delone',
                            visible: function (row) {
                                return Config.childrenAdminIds.indexOf(row.admin_id) > -1;
                            }
                        }],
                        formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            var submitForm = function (ids, layero) {
                var options = table.bootstrapTable('getOptions');
                var columns = [];
                $.each(options.columns[0], function (i, j) {
                    if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                        columns.push(j.field);
                    }
                });
                var search = options.queryParams({});
                $("input[name=search]", layero).val(options.searchText);
                $("input[name=ids]", layero).val(ids);
                $("input[name=filter]", layero).val(search.filter);
                $("input[name=op]", layero).val(search.op);
                $("input[name=columns]", layero).val(columns.join(','));
                $("form", layero).submit();
            };

            $(document).on("click", ".btn-gotocjt", function () {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                console.log(ids, page, all);
                Layer.confirm("请选择一键询价的选项<form action='" + Fast.api.fixurl("caijiaku/material_inventory/gotocjt") + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                    title: '一键询价数据',
                    btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success: function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }
                    , yes: function (index, layero) {
                        submitForm(ids.join(","), layero);
                        return false;
                    }
                    ,
                    btn2: function (index, layero) {
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        submitForm(ids.join(","), layero);
                        return false;
                    }
                    ,
                    btn3: function (index, layero) {
                        submitForm("all", layero);
                        return false;
                    }
                })
            });

            $(document).on("click",'#btn-import-file',function() {
                Fast.api.open("caijiaku/material_inventory/import", "上传材价");
            });
            $(document).on("click",'.btn-projectedit',function() {
                Fast.api.open("caijiaku/material_inventory/projectedit", "按项目编辑", {area:["50%","50%"]});
            });
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='admin_id']", form).addClass("selectpage").data("source", "auth/admin/index").data("primaryKey", "nickname").data("field", "nickname").data("orderBy", "id desc");
            });
            $(document).on("click",'#one-cate .radio label',function() {
                var cateid = $(this).data('id');
                $(this).addClass("selected").siblings().removeClass("selected");
                oneCate = category.find(item => item.id === cateid);
                if (oneCate && oneCate.categorylist.length > 0) {
                    var html = '<div class="radio" >';
                    for (var i = 0; i < oneCate.categorylist.length; i++) {
                        html += '<label data-id="'+oneCate.categorylist[i].id+'" for="category2-'+oneCate.categorylist[i].id+'"><input id="category2-'+oneCate.categorylist[i].id+'" type="radio" name="category2" value="'+oneCate.categorylist[i].id+'">'+oneCate.categorylist[i].name+'</label>';
                    }
                    html += '</div>';
                    $('#two-cate').removeClass('hide')
                    $('#two-cate .input-group').html(html);
                    $('#three-cate, #four-cate').addClass('hide');
                    $('#three-cate .input-group,#four-cate .input-group').html('');
                }
            });
            $(document).on("click",'#two-cate .radio label',function() {
                var cateid = $(this).data('id');
                $(this).addClass("selected").siblings().removeClass("selected");
                twoCate = oneCate.categorylist.find(item => item.id === cateid);
                if (twoCate && twoCate.categorylist.length > 0) {
                    var html = '<div class="radio" >';
                    for (var i = 0; i < twoCate.categorylist.length; i++) {
                        html += '<label data-id="'+twoCate.categorylist[i].id+'" for="category3-'+twoCate.categorylist[i].id+'"><input id="category3-'+twoCate.categorylist[i].id+'" type="radio" name="category3" value="'+twoCate.categorylist[i].id+'">'+twoCate.categorylist[i].name+'</label>';
                    }
                    html += '</div>';
                    $('#three-cate').removeClass('hide')
                    $('#three-cate .input-group').html(html);
                    $('#four-cate').addClass('hide');
                    $('#four-cate .input-group').html('');
                }
            });
            $(document).on("click",'#three-cate .radio label',function() {
                var cateid = $(this).data('id');
                $(this).addClass("selected").siblings().removeClass("selected");
                threeCate = twoCate.categorylist.find(item => item.id === cateid);
                $.ajax({
                    url: "caijiaku/material_inventory/getMaterialList",
                    data: {cateid: cateid},
                    type: "post",
                    success: function (res) {
                        if (res.code == 1) {
                            var data = res.data
                            var html = '<div class="radio" >';
                            for (var i = 0; i < data.length; i++) {
                                html += '<label data-id="'+data[i].id+'" for="category4-'+data[i].id+'"><input id="category4-'+data[i].id+'" type="radio" name="material_id" value="'+data[i].id+'">'+data[i].name+'</label>';
                            }
                            html += '</div>';
                            $('#four-cate').removeClass('hide')
                            $('#four-cate .input-group').html(html);
                            if (data.length == 1) {
                                $('#four-cate .radio label').eq(0).trigger('click');
                            }
                        } else {
                            layer.msg(res.msg);
                            return false;
                        }
                    }
                })
            });
            $(document).on("click",'#four-cate .radio label',function() {
                var cateid = $(this).data('id');
                $(this).addClass("selected").siblings().removeClass("selected");
                table.bootstrapTable('refresh');
            })
            $(document).on("click", 'input[type="reset"]', function () {
                setTimeout(function () {
                    $('#one-cate .radio label').removeClass('selected')
                    $('#two-cate,#three-cate, #four-cate').addClass('hide');
                    $('#two-cate .input-group,#three-cate .input-group,#four-cate .input-group').html('');
                    oneCate = []
                    twoCate = []
                    threeCate = []
                    table.bootstrapTable('refresh');
                }, 1);
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'caijiaku/material_inventory/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'caijiaku/material_inventory/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'caijiaku/material_inventory/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        import:function() {
            $(document).on("click",'#addproject',function() {
                Fast.api.open("project/add", "新建项目", {area:["80%","80%"]});
            });
            Controller.api.bindevent();
        },
        projectedit:function() {
            Controller.api.bindevent();
        },
        eslist: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'caijiaku/material_inventory/eslist' + location.search,
                    table: 'eslist',
                }
            });
            console.log('type', Config.type)
            var columnvisible = {
                'fax':{
                    'tax':true,
                    'brandname':true,
                    'suppliername':true,
                },
                'gov':{
                    'tax':false,
                    'brandname':false,
                    'suppliername':false,
                },
                'mix':{
                    'tax':true,
                    'brandname':false,
                    'suppliername':false,
                },
                'inquiry':{
                    'tax':false,
                    'brandname':false,
                    'suppliername':false,
                }
            }
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {field: 'no',
                            title: __('序号'),
                            sortable: true,
                            operate:false,
                            align: "center",
                            width: 40,
                            formatter: function (value, row, index) {
                                //获取每页显示的数量
                                var pageSize=table.bootstrapTable('getOptions').pageSize;
                                //获取当前是第几页
                                var pageNumber=table.bootstrapTable('getOptions').pageNumber;
                                //返回序号，注意index是从0开始的，所以要加上1
                                return pageSize * (pageNumber - 1) + index + 1;
                            }
                        },
                        {field: 'title', title: __('Title'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'own_spec', title: __('Own_spec'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'unit', title: __('Unit'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'showdate', title: __('Showdate'), operate:false, addclass:'datetimerange', autocomplete:false},
                        {field: 'price', title: __('含税价'), operate:false},
                        {field: 'tax', title: __('Tax'), operate:false, visible: columnvisible[Config.type].tax},
                        {field: 'areaname', title: __('Areaname'), operate: false},
                        {field: 'brandname', title: __('Brandname'), operate: false, visible: columnvisible[Config.type].brandname},
                        {field: 'suppliername', title: __('Suppliername'), operate: false, visible: columnvisible[Config.type].suppliername},
                    ]
                ],
                search: !1,
                commonSearch: !1,
                dblClickToEdit:!1,
                showExport:false,
                showColumns:false,
                showToggle:false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        trend: function () {
            // 基于准备好的dom，初始化echarts实例
            var lineChart = Echarts.init(document.getElementById('echart'), 'walden');

            // 指定图表的配置项和数据
            var option = {
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: Config.column
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    data: Config.userdata,
                    name: __('价格'),
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        normal: {
                            width: 1.5
                        }
                    },
                }]
            };

            // 使用刚指定的配置项和数据显示图表。
            lineChart.setOption(option);
            $(window).resize(function () {
                lineChart.resize();
            });

            $(document).on("click", ".btn-refresh", function () {
                setTimeout(function () {
                    lineChart.resize();
                }, 0);
            });
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'caijiaku/material_inventory/trend' + location.search,
                    table: 'trend',
                }
            });
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {field: 'no',
                            title: __('序号'),
                            sortable: true,
                            operate:false,
                            align: "center",
                            width: 40,
                            formatter: function (value, row, index) {
                                //获取每页显示的数量
                                var pageSize=table.bootstrapTable('getOptions').pageSize;
                                //获取当前是第几页
                                var pageNumber=table.bootstrapTable('getOptions').pageNumber;
                                //返回序号，注意index是从0开始的，所以要加上1
                                return pageSize * (pageNumber - 1) + index + 1;
                            }
                        },
                        {field: 'title', title: __('Title'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'own_spec', title: __('Own_spec'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'unit', title: __('Unit'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'showdate', title: __('Showdate'), operate:false, addclass:'datetimerange', autocomplete:false},
                        {field: 'price', title: __('含税价'), operate:false},
                        {field: 'tax', title: __('Tax'), operate:false, visible: true},
                        {field: 'areaname', title: __('Areaname'), operate: false},
                        {field: 'brandname', title: __('Brandname'), operate: false, visible: true},
                    ]
                ],
                search: !1,
                commonSearch: !1,
                dblClickToEdit:!1,
                showExport:false,
                showColumns:false,
                showToggle:false,
                pagination:false
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            formatter: {
                faxtab: function (value, row, index) {
                    return '<a href="caijiaku/material_inventory/eslist?type=fax&id='+row.id+'"  data-value="' + row.id + '" class="dialogit" title="【'+row.title+'】'+__('Faxprice')+'">'+row.faxnum+'条</a>'
                },
                govtab: function (value, row, index) {
                    return '<a href="caijiaku/material_inventory/eslist?type=gov&id='+row.id+'"  data-value="' + row.id + '" class="dialogit" title="【'+row.title+'】'+__('Govprice')+'">'+row.govnum+'条</a>'
                },
                mixtab: function (value, row, index) {
                    return '<a href="caijiaku/material_inventory/eslist?type=mix&id='+row.id+'"  data-value="' + row.id + '" class="dialogit" title="【'+row.title+'】'+__('专业测定价')+'">'+row.mixnum+'条</a>'
                },
                inquirytab: function (value, row, index) {
                    return '<a href="caijiaku/material_inventory/eslist?type=inquiry&id='+row.id+'"  data-value="' + row.id + '" class="dialogit" title="【'+row.title+'】'+__('Inquiryprice')+'">'+row.inquirynum+'条</a>'
                },
                trend: function (value, row, index) {
                    return '<a href="caijiaku/material_inventory/trend?id='+row.id+'"  data-value="' + row.id + '" class="dialogit" title="【'+row.title+'】'+__('走势图')+'"><i class="fa fa-line-chart"></i></a>'
                },
            },
            bindevent: function () {
                $("#c-material_id").data("eSelect", function(data){
                    //后续操作
                    $('#c-materialname').val(data.name)
                });
                let originalData = []; // 用于存储原始数据
                let batchtimes = 0;
                let curtimes = 0;
                let lastrow = 0;
                $("#c-file").change(function () {
                    var marketyulanfile = $(this).val();
                    if (marketyulanfile) {
                        $.ajax({
                            url: "caijiaku/material_inventory/import_preview",
                            data: {marketyulanfile: marketyulanfile},
                            type: "post",
                            success: function (res) {
                                if (res.code == 1) {
                                    originalData = res.data.data;
                                    batchtimes = res.data.batchtimes;
                                    layer.msg(res.msg,{time:1000},function (){
                                        var htm = `<table class="table table-striped table-config" id="normaledit">
                                                      <tbody>
                                                      <tr>
                                                        <td width="60">Excel行号</td>
                                                        <td width="50">类别</td>
                                                        <td>材料名称</td>
                                                        <td width="100">规格型号</td>
                                                        <td>评审价(含税)</td>
                                                        <td width="60">单位</td>
                                                        <td width="100">报价日期</td>
                                                        <td width="60">税率%</td>
                                                        <td width="60">品牌</td>
                                                        <td width="60">地区</td>
                                                        <td>供应商</td>
                                                        <td style="min-width:100px">材料图片</td>
                                                      </tr>
                                                      `;
                                        for (var i=0;i<originalData.length;i++){
                                            numcount = originalData[i].hang
                                            htm += `<tr>
                                                        <td>${originalData[i].hang}</td>
                                                        <td>${originalData[i].catename}</td>
                                                        <td>${originalData[i].title}</td>
                                                        <td>${originalData[i].own_spec}</td>
                                                        <td>${originalData[i].price}</td>
                                                        <td>${originalData[i].unit}</td>
                                                        <td>${originalData[i].showdate}</td>
                                                        <td>${originalData[i].tax}</td>
                                                        <td>${originalData[i].brandname}</td>
                                                        <td>${originalData[i].areaname}</td>
                                                        <td>${originalData[i].suppliername}</td>`;
                                            if (originalData[i].images) {
                                                var images = originalData[i].images.split(',');
                                                htm += `<td><ul class="row list-inline"><input type="hidden" class="input-images" name="row[`+numcount+`][images]" value="${originalData[i].images}">`;
                                                for(var j=0;j<images.length;j++) {
                                                    htm += `<li ><a href="#" class="thumbnail" style="display:block"><img src="${images[j]}" style="width:50px;height:50px;object-fit: contain;"></a><a href="javascript:void(0)" data-img="${images[j]}" class="btn btn-danger btn-xs btn-trash remove-image" style="display:block"><i class="fa fa-trash"></i></a></li>`
                                                }
                                                htm += `</ul></td>`;
                                            } else {
                                                htm += `<td></td>`;
                                            }
                                            htm += ` </tr>`;
                                        }
                                        htm += `</tbody>
                                                    </table><img id="hiddenImg" style="display:none;">`;
                                        $("#wechat").empty();
                                        $("#wechat").html(htm);
                                    });
                                } else {
                                    layer.msg(res.msg);
                                    return false;
                                }
                            }
                        });
                    }
                });
                
                $(document).on('click', '#normaledit img', function(){
                    var image = $(this).attr('src');
                    var hiddenImg = document.getElementById('hiddenImg');
                    hiddenImg.src = image;
                    var imageWidth = hiddenImg.width
                    var imageHeight = hiddenImg.height
                    imageWidth = imageWidth > 800 ? 800 : imageWidth
                    imageHeight = imageHeight > 800 ? 800 : imageHeight
                    console.log('imageWidth', imageWidth,imageHeight)
                    layer.open({
                        type: 1,
                        shadeClose: true,
                        title: false,
                        closeBtn: 0,
                        shade: 0.8,
                        area: [imageWidth+'px', imageHeight+'px'],
                        content: '<img src="' + image + '" style="width:100%;">'
                    });
                });
                $(document).on('click', '#normaledit .remove-image', function(){
                    var image = $(this).data('img');
                    var inputImages = $(this).parents('ul.row').find('input.input-images');
                    var images = inputImages.val().split(',');
                    var index = images.indexOf(image);
                    if (index > -1) {
                        images.splice(index, 1);
                    }
                    console.log('images', images,images.join(','))
                    inputImages.val(images.length ? images.join(',') : '');
                    $(this).parents('li').remove();
                })
                var collectModifiedData = function() {
                    let modifiedData = {};
                    // 获取所有相关的 input 元素
                    const inputs = $(' .input-images');
                    // 创建一个映射，用于快速查找 input 元素
                    const inputMap = {};
                    inputs.each(function () {
                        const name = $(this).attr('name');
                        const hang = name.match(/\[(\d+)\]\[/)[1];
                        inputMap[hang] = inputMap[hang] || {};
                        inputMap[hang][name] = this;
                    });

                    for (var i = 0; i < originalData.length; i++) {
                        numcount = originalData[i].hang;
                        // 检查是否有对应的 input 元素
                        if (!inputMap[numcount]) continue;

                        const currentRow = {
                            hang: originalData[i].hang,
                            images: $(inputMap[numcount]['row[' + numcount + '][images]']).val() || '',
                        };
                        // 检查是否有修改
                        // if (currentRow.cha_materialname !== originalData[i].cha_materialname ||
                        //     currentRow.cha_material_id !== originalData[i].cha_material_id ||
                        //     currentRow.images !== originalData[i].images) {
                            
                        //     modifiedData[numcount] = currentRow;
                        // }
                        modifiedData[numcount] = currentRow;
                    }
                    return modifiedData;
                }
                var submit = function(form, success, error, submit) {
                    if (form.size() === 0) {
                        Toastr.error("表单未初始化完成,无法提交");
                        return false;
                    }
                    if (typeof submit === 'function') {
                        if (false === submit.call(form, success, error)) {
                            return false;
                        }
                    }
                    var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                    type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                    var url = form.attr("action");
                    url = url ? url : location.href;
                    // 调整 serialize 方法以收集修改过的数据
                    var modifiedData = collectModifiedData();
                    var file = form.find("input[name=file]");
                    // 构建最终的提交数据
                    var params = $.param({row: modifiedData, file: file.size() > 0 ? file.val() : '', 'curtimes':curtimes, lastrow, project_name:$('#c-project_name').val()});
                    // 修复当存在多选项元素时提交的 BUG
                    var multipleList = $("[name$='[]']", form);
                    if (multipleList.size() > 0) {
                        var postFields = form.serializeArray().map(function (obj) {
                            return obj.name;
                        });
                        $.each(multipleList, function (i, j) {
                            if (postFields.indexOf($(this).prop("name")) < 0) {
                                params[$(this).prop("name")] = '';
                            }
                        });
                    }
                
                    // 调用 Ajax 请求方法
                    // 返回一个新的Promise对象
                    return new Promise(function(resolve, reject) {
                        Fast.api.ajax({
                            type: type,
                            url: url,
                            data: params,
                            dataType: 'json',
                            complete: function (xhr) {
                                var token = xhr.getResponseHeader('__token__');
                                if (token) {
                                    $("input[name='__token__']").val(token);
                                }
                            }
                        }, function (data, ret) {
                            $('.form-group', form).removeClass('has-feedback has-success has-error');
                            if (data && typeof data === 'object') {
                                // 刷新客户端 token
                                if (typeof data.token !== 'undefined') {
                                    $("input[name='__token__']").val(data.token);
                                }
                                // 调用客户端事件
                                if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                                    data.callback.call(form, data);
                                }
                            }
                            if (typeof success === 'function') {
                                if (false === success.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            resolve(ret); // 解析Promise
                        }, function (data, ret) {
                            if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                                $("input[name='__token__']").val(data.token);
                            }
                            if (typeof error === 'function') {
                                if (false === error.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            reject(ret); // 拒绝Promise
                        });
                        return true;
                    });
                }
                $('#import-submit').click(function () {
                    var that = this,
                    project_name = $('#c-project_name').val(),
                    form = $('#import-form'),
                    submitBtn = $(".layer-footer [type=submit]", form);
                    if (project_name == '') {
                        Toastr.error("请输入项目名称");
                    }
                    submitBtn.addClass("disabled");
                    async function submitForm(i) {
                        curtimes = i;
                        try {
                            const rets = await submit(form, function(data, ret){
                                console.log('submitForm', data, ret)
                                if (ret.code == 1) {
                                    lastrow = ret.data.lastrow;
                                }
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                    // 提示及关闭当前窗口
                                    var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                                    parent.Toastr.success(msg);
                                    parent.$(".btn-refresh").trigger("click");
                                    var index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                }
                            }, function(data, ret){
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                }
                            });
                            // 如果需要根据`ret`做进一步处理
                            // console.log('Submit result:', rets);
                        } catch (error) {
                            // 处理错误情况
                            console.error('Error submitting form:', error);
                        }
                    }
                    
                    (async function processNext() {
                        for (let i = 0; i < batchtimes; i++) {
                            await submitForm(i); // 等待当前提交完成
                        }
                    })();
                    
                    return false
                })
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
